import {
    StyleSheet,
    Text,
    View,
    ImageBackground,
    ScrollView,
    Pressable,
    TextInput,
    Animated,
    Easing,
} from 'react-native';
import React, { useState, useRef } from 'react';
import { useRoute, useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import { FocusAwareStatusBar } from '~/components';
import { px2dp, scale } from '~/utils/px2dp';
import { useTranslation } from 'react-i18next';
import { useAuthCode } from '~/common';
import { checkRegVerifyEmailCode, recoveredPasswordApi, eMailRegApi } from '~/api/loginApi';

export default function CheckEmailCode() {
    const { t } = useTranslation();
    const { fetchAuthCode, countDown, loading } = useAuthCode();
    const router: any = useRoute();
    const navigation = useNavigation<any>();
    const { type, uid, email, pwd } = router.params || {};
    const [code, setCode] = useState<string[]>(['', '', '', '', '', '']);
    const [isError, setIsError] = useState<boolean>(false);
    const inputs = useRef<TextInput[]>([]);
    const shakeAnimation = useRef(new Animated.Value(0)).current;
    const handleChangeText = (text: string, index: number) => {
        const newCode = [...code];
        newCode[index] = text;
        setCode(newCode);
        if (text && index < 5) {
            inputs.current[index + 1]?.focus();
        }
        if (index === 5 && text) {
            validateCode(newCode.join(''));
        }
    };
    // 校验验证码
    const validateCode = (enteredCode: string) => {
        checkRegVerifyEmailCode({ uid, code: enteredCode }).then((res) => {
            if (res.status == 1) {
                setIsError(false);
                if (type == 'register') {
                    // 开始注册
                    eMailReg();
                } else {
                    // 密码修改
                    recoveredPassword();
                }
            } else {
                setIsError(true);
                startShakeAnimation();
                Toast.show({ content: t('CheckEmailCode.t1'), layout: 'top' });
            }
        });
    };
    // 修改密码
    const recoveredPassword = () => {
        recoveredPasswordApi({ email, password: pwd }).then((res) => {
            if (res.status == 1) {
                Toast.show({ content: t('CheckEmailCode.t2'), layout: 'top' });
                navigation.navigate('LoginByEmail');
            } else {
                if (res.msg == '与上次密码相同') {
                    Toast.show({ content: t('CheckEmailCode.t3'), layout: 'top' });
                    navigation.goBack();
                } else {
                    Toast.show({ content: t('CheckEmailCode.t4'), layout: 'top' });
                    navigation.goBack();
                }
            }
        });
    };
    // 注册
    const eMailReg = () => {
        eMailRegApi({ email, password: pwd }).then((res) => {
            if (res.status == 1) {
                Toast.show({ content: t('CheckEmailCode.t5'), layout: 'top' });
                navigation.navigate('LoginByEmail');
            } else {
                if (res.msg == '邮箱已存在 ') {
                    Toast.show({ content: t('CheckEmailCode.t6'), layout: 'top' });
                    navigation.goBack();
                } else {
                    Toast.show({ content: t('CheckEmailCode.t7'), layout: 'top' });
                    navigation.goBack();
                }
            }
        });
    };

    const startShakeAnimation = () => {
        Animated.sequence([
            Animated.timing(shakeAnimation, {
                toValue: 10,
                duration: 50,
                easing: Easing.linear,
                useNativeDriver: true,
            }),
            Animated.timing(shakeAnimation, {
                toValue: -10,
                duration: 50,
                easing: Easing.linear,
                useNativeDriver: true,
            }),
            Animated.timing(shakeAnimation, {
                toValue: 10,
                duration: 50,
                easing: Easing.linear,
                useNativeDriver: true,
            }),
            Animated.timing(shakeAnimation, {
                toValue: 0,
                duration: 50,
                easing: Easing.linear,
                useNativeDriver: true,
            }),
        ]).start();
    };
    // 处理退格键
    const handleKeyPress = (event: any, index: number) => {
        if (event.nativeEvent.key === 'Backspace' && index > 0 && !code[index]) {
            inputs.current[index - 1]?.focus();
        }
    };

    const shakeStyle = {
        transform: [{ translateX: shakeAnimation }],
    };
    return (
        <View style={styles.container}>
            <FocusAwareStatusBar translucent={true} />
            <ImageBackground style={styles.bg} source={require('~/assets/login/bg4.png')}>
                <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.contentContainerStyle}>
                    <Pressable style={styles.close} onPress={() => navigation.goBack()}>
                        <Icon name={'close-sharp'} size={px2dp(60)} color={'#fff'}></Icon>
                    </Pressable>
                    <View style={styles.bg_content}>
                        <Text style={styles.title}>{t('CheckEmailCode.t8')}</Text>
                        <Text style={styles.t2}>
                            {t('CheckEmailCode.t9')} {email}
                        </Text>
                    </View>
                    <View style={styles.content}>
                        <Animated.View style={[styles.codeContainer, isError && styles.errorContainer, shakeStyle]}>
                            {code.map((digit, index) => (
                                <TextInput
                                    key={index}
                                    style={[styles.codeInput, isError && styles.errorInput]}
                                    maxLength={1}
                                    keyboardType="numeric"
                                    onChangeText={(text) => handleChangeText(text, index)}
                                    onKeyPress={(event) => handleKeyPress(event, index)}
                                    ref={(ref) => {
                                        if (ref) {
                                            inputs.current[index] = ref;
                                        }
                                    }}
                                    value={digit}
                                />
                            ))}
                        </Animated.View>
                        {isError && <Text style={styles.errorText}>{t('CheckEmailCode.t10')}</Text>}
                    </View>
                    <View style={styles.bottom}>
                        <Pressable
                            disabled={loading || !!countDown}
                            onPress={() => fetchAuthCode(email, 'actionEmaile')}>
                            <Text style={[styles.grayText]}>
                                {countDown || t('CheckEmailCode.t11')} {countDown && 's' + t('CheckEmailCode.t11')}
                            </Text>
                        </Pressable>
                    </View>
                </ScrollView>
            </ImageBackground>
        </View>
    );
}

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    container: {
        flex: 1,
        // backgroundColor: '#fff',
    },
    contentContainerStyle: {
        flexGrow: 1,
    },
    bg: {
        flex: 1,
        resizeMode: 'contain',
        paddingHorizontal: px2dp(24),
        position: 'relative',
    },
    close: {
        position: 'absolute',
        top: '5%',
    },
    bg_content: {
        marginTop: '30%',
    },
    title: {
        color: '#fff',
        fontSize: px2dp(40),
        fontWeight: 'bold',
    },
    t2: {
        marginTop: px2dp(12),
        color: '#fff',
        fontSize: scale(24),
        fontWeight: '400',
    },
    content: {
        padding: px2dp(32),
        paddingTop: px2dp(64),
        marginTop: -px2dp(32),
        borderTopLeftRadius: px2dp(32),
        borderTopRightRadius: px2dp(32),
        justifyContent: 'center',
        alignItems: 'center',
    },

    codeContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        width: '100%',
    },
    errorContainer: {
        borderColor: 'red',
    },
    errorInput: {
        borderColor: 'red',
    },
    errorText: {
        marginTop: px2dp(24),
        color: 'red',
        fontSize: px2dp(28),
    },
    codeInput: {
        width: px2dp(80),
        height: px2dp(80),
        backgroundColor: '#F6F8FA',
        borderRadius: px2dp(12),
        textAlign: 'center',
        fontSize: scale(30),
    },
    grayText: {
        color: '#25C8C8',
        fontSize: scale(28),
    },
    bottom: {
        marginHorizontal: px2dp(32),
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    t1: {
        color: '#666666',
        fontSize: scale(24),
    },
});
